package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.sys.CommConstant;
import com.yxt.common.sys.CommUtil;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.widget.ListWheelAdapter;
import com.yxt.common.widget.OnWheelChangedListener;
import com.yxt.common.widget.WheelView;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Division;
import com.yxt.model.Valley;
import com.yxt.service.DivisionService;
import com.yxt.service.ValleyService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

/**
 * 雨情汇总
 * @author crazyman
 */
public class RainStationTotalActivity extends Activity {
	private static final int MENU_MAXCOUNT = Menu.FIRST+1;
	private static final int MENU_KJFB = Menu.FIRST + 2;
	private static final int MENU_INTERVAL = Menu.FIRST + 3;

	private String[] shiduan = {"qiangdu","1","3","6","24"};
	private String[] qiangdu = {">=250","100-250","50-100","25-100","10-25","<10"};
	private String[] strength = {"6","5","4","3","2","1"};
	private int[] to = {R.id.lbl1,R.id.lbl2,R.id.lbl3,R.id.lbl4,R.id.lbl5};
	private DivisionService diviservice = new DivisionService(RainStationTotalActivity.this);
	private ValleyService vallservice = new ValleyService(RainStationTotalActivity.this);
	private TextView lblProvince;
	private TextView lblRiver;
	private List<Division> provinces;
	private List<Division> cities;
	private List<Division> county;
	private List<Valley> mainriver;
	private List<Valley> childriver;
	private List<Map<String,String>> datalst = new ArrayList<Map<String,String>>();
	private String comment = "";
	private TextView lblRainMessage;
	private TextView lblRainTime;
	private ListView lstRainList;
	private ProgressDialog dialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.rain_total);   //软件activity的布局
		ActivityStackControlUtil.add(this);
		
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		lblRainMessage = (TextView)findViewById(R.id.lblRainMessage);
		lblRainTime = (TextView)findViewById(R.id.lblRainTime);	
		lstRainList = (ListView) findViewById(R.id.lstRainList);
		
		lblProvince = (TextView)findViewById(R.id.lblProvince);
		lblRiver = (TextView)findViewById(R.id.lblRiver);
		lblProvince.setText(CommConstant.Main.CURRENT_AREA_NAME);
		lblRiver.setText(CommConstant.Main.CURRENT_RIVER_NAME);
		
		lblProvince.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				View view = View.inflate(RainStationTotalActivity.this, R.layout.comm_region, null);
				final AlertDialog menuDialog = new AlertDialog.Builder(RainStationTotalActivity.this).create();
				menuDialog.setView(view);
				menuDialog.show();
				final WheelView wheelProvince = (WheelView)view.findViewById(R.id.wheelProvince);
				final WheelView wheelCity = (WheelView)view.findViewById(R.id.wheelCity);
				final WheelView wheelCounty = (WheelView)view.findViewById(R.id.wheelCounty);
				String area = CommUtil.getDefaultAreaSql();				
				//获取区域列表
				provinces = diviservice.getDivisionByConditions(area);
				int currprovince = CommUtil.getCurrentRegionIndex(provinces, CommConstant.Main.CURRENT_AREA_CODE, CommConstant.Main.DEFAULT_PROVINCE_TYPE);
				cities = diviservice.getDivisionByConditions("type = '"+CommConstant.Rain.CITY_TYPE+"' and parentCode='" + provinces.get(currprovince).getCode()+"'");
				int currcity = CommUtil.getCurrentRegionIndex(cities, CommConstant.Main.CURRENT_AREA_CODE, CommConstant.Main.DEFAULT_CITY_TYPE);
				county = diviservice.getDivisionByConditions("type = '"+CommConstant.Rain.COUNTY_TYPE+"' and parentCode='" + cities.get(currcity).getCode()+"'");
				int currcounty = CommUtil.getCurrentRegionIndex(county, CommConstant.Main.CURRENT_AREA_CODE, CommConstant.Main.DEFAULT_COUNTY_TYPE);
				//设置当前项
				wheelProvince.setAdapter(new ListWheelAdapter<Division>(provinces,CommConstant.Config.REGION_MAXLENGTH));
				wheelCity.setAdapter(new ListWheelAdapter<Division>(cities,CommConstant.Config.REGION_MAXLENGTH));
				wheelCounty.setAdapter(new ListWheelAdapter<Division>(county,CommConstant.Config.REGION_MAXLENGTH));
				wheelProvince.setCurrentItem(currprovince);
				wheelCity.setCurrentItem(currcity);
				wheelCounty.setCurrentItem(currcounty);
				//添加事件
				wheelProvince.addChangingListener(new OnWheelChangedListener(){
					public void onChanged(WheelView wheel, int oldValue, int newValue) {
						cities = diviservice.getDivisionByConditions("type = '"+CommConstant.Rain.CITY_TYPE+"' and parentCode = '"+provinces.get(wheelProvince.getCurrentItem()).getCode()+"'");
						wheelCity.setAdapter(new ListWheelAdapter<Division>(cities,CommConstant.Config.REGION_MAXLENGTH));
					}
				});
				wheelCity.addChangingListener(new OnWheelChangedListener(){
					public void onChanged(WheelView wheel, int oldValue, int newValue) {
						county = diviservice.getDivisionByConditions("type = '"+CommConstant.Rain.COUNTY_TYPE+"' and parentCode = '"+cities.get(wheelCity.getCurrentItem()).getCode()+"'");	
						wheelCounty.setAdapter(new ListWheelAdapter<Division>(county,CommConstant.Config.REGION_MAXLENGTH));			
					}
				});
				
				Button btnConfirm = (Button)view.findViewById(R.id.btnConfirm);
				Button btnCancel = (Button)view.findViewById(R.id.btnCancel);
				btnConfirm.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						Division proDivision = provinces.get(wheelProvince.getCurrentItem());
						Division cityDivision = cities.get(wheelCity.getCurrentItem());
						Division countyDivision = county.get(wheelCounty.getCurrentItem());
						if (!CommConstant.Config.DEFAULT_NAME.equals(countyDivision.getName())) {
							CommConstant.Main.CURRENT_AREA_CODE = countyDivision.getCode();
							CommConstant.Main.CURRENT_AREA_NAME = countyDivision.getName();
							lblProvince.setText(countyDivision.getName());
						} else {
							if (!CommConstant.Config.DEFAULT_NAME.equals(cityDivision.getName())) {
								CommConstant.Main.CURRENT_AREA_CODE = cityDivision.getCode();
								CommConstant.Main.CURRENT_AREA_NAME = cityDivision.getName();
								lblProvince.setText(cityDivision.getName());
							} else {
								CommConstant.Main.CURRENT_AREA_CODE = proDivision.getCode();
								CommConstant.Main.CURRENT_AREA_NAME = proDivision.getName();
								lblProvince.setText(proDivision.getName());
							}
						}
						menuDialog.cancel();
						CommUtil.persistenceAreaInfo(getApplicationContext());
						initComponent();
					}			
				});
				btnCancel.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						menuDialog.cancel();
					}			
				});
			}			
		});
		lblRiver.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				View view = View.inflate(RainStationTotalActivity.this, R.layout.comm_river, null);
				final AlertDialog menuDialog = new AlertDialog.Builder(RainStationTotalActivity.this).create();
				menuDialog.setView(view);
				menuDialog.show();
				final WheelView wheelRiver = (WheelView)view.findViewById(R.id.wheelRiver);
				final WheelView wheelSubRiver = (WheelView)view.findViewById(R.id.wheelSubRiver);
				String mriver = CommUtil.getDefaultRiverSql(CommConstant.Water.DEFAULT_MAIN_RIVER);
				if (mriver.indexOf("type") == -1) {
					mriver += " and type = '"+CommConstant.Water.MAIN_TYPE+"'";
				}
				mainriver = vallservice.getValleyByCondtion(mriver);
				String sriver = CommUtil.getDefaultRiverSql(CommConstant.Water.DEFAULT_SUB_RIVER);
				int currmain = CommUtil.getCurrentRiverIndex(mainriver, CommConstant.Main.CURRENT_RIVER_CODE, CommConstant.Main.DEFAULT_MAIN_TYPE);
				if (sriver.indexOf("type") > -1) {//判断是否为空
					sriver += " and parentCode = '"+mainriver.get(currmain).getCode()+"'";
				} else {
					sriver += " and type = '"+CommConstant.Water.SUB_TYPE+"' and parentCode = '"+mainriver.get(currmain).getCode()+"'";
				}
				childriver = vallservice.getValleyByCondtion(sriver);
				int currsub = CommUtil.getCurrentRiverIndex(childriver, CommConstant.Main.CURRENT_RIVER_CODE, CommConstant.Main.DEFAULT_SUB_TYPE);
				wheelRiver.setAdapter(new ListWheelAdapter<Valley>(mainriver,CommConstant.Config.RIVER_MAXLENGTH));
				wheelSubRiver.setAdapter(new ListWheelAdapter<Valley>(childriver,CommConstant.Config.RIVER_MAXLENGTH));
				wheelRiver.setCurrentItem(currmain);
				wheelSubRiver.setCurrentItem(currsub);
				//添加事件
				wheelRiver.addChangingListener(new OnWheelChangedListener(){
					public void onChanged(WheelView wheel, int oldValue, int newValue) {
						childriver = vallservice.getValleyByCondtion("type = '"+CommConstant.Water.SUB_TYPE+"' and parentCode = '"+mainriver.get(wheelRiver.getCurrentItem()).getCode()+"'");
						wheelSubRiver.setAdapter(new ListWheelAdapter<Valley>(childriver,CommConstant.Config.RIVER_MAXLENGTH));
					}
				});
				
				Button btnConfirm = (Button)view.findViewById(R.id.btnConfirm);
				Button btnCancel = (Button)view.findViewById(R.id.btnCancel);
				btnConfirm.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						Valley subValley = childriver.get(wheelSubRiver.getCurrentItem());
						Valley mainValley = mainriver.get(wheelRiver.getCurrentItem());
						if (!CommConstant.Config.DEFAULT_NAME.equals(subValley.getName())) {
							CommConstant.Main.CURRENT_RIVER_CODE = subValley.getCode();
							CommConstant.Main.CURRENT_RIVER_NAME = subValley.getName();
							lblRiver.setText(subValley.getName());
						} else {
							CommConstant.Main.CURRENT_RIVER_CODE = mainValley.getCode();
							CommConstant.Main.CURRENT_RIVER_NAME = mainValley.getName();
							lblRiver.setText(mainValley.getName());
						}
						CommUtil.persistenceRiverInfo(getApplicationContext());
						menuDialog.cancel();
						initComponent();
					}			
				});
				btnCancel.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						menuDialog.cancel();
					}			
				});
			}			
		});
		
		ImageView lblTitle1 = (ImageView)findViewById(R.id.lblTitle1);	
		lblTitle1.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				initComponent();
			}			
		});
				
		initComponent();
	}
	
	private void initComponent(){	
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					RainTotalTableAdapter adapter = new RainTotalTableAdapter(getApplicationContext(),datalst,R.layout.rain_total_item,shiduan,to);
					lstRainList.setAdapter(adapter);
					if (CommConstant.Rain.RIVER_ALL.equals(CommConstant.Main.CURRENT_RIVER_NAME)) {
						comment = comment.replace(CommConstant.Water.DEFAULT_PALCEHOLDER, "<font color=\"#FF9900\">"+CommConstant.Main.CURRENT_AREA_NAME+"</font>");
					} else {
						comment = comment.replace(CommConstant.Water.DEFAULT_PALCEHOLDER, "<font color=\"#FF9900\">"+CommConstant.Main.CURRENT_AREA_NAME + "." + CommConstant.Main.CURRENT_RIVER_NAME +"</font>");
					}
					lblRainMessage.setText(Html.fromHtml(comment)); 
					lblRainTime.setText(CommConstant.Rain.CALC_TIME); 
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadRainList();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}
	
	private void downloadRainList() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new RainHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}
	}

	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();
		String itemId = intent.getStringExtra("itemId");
		Map<String, String> menu = CommConstant.Main.FUNCTIONS.get(CommConstant.Main.CURRENT_TEMPLATE_CODE).get(itemId);
		String server = menu.get("server");
		CommConstant.Sever.RAIN_SERVER = server;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"rainlist.xml");
		} else {
			URL url = new URL(server + "rain/CountInfo.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();			
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}
	
	private class RainHandler extends DefaultHandler {
		private Map<String,String> data = new HashMap<String,String>();
		private int position = 0;

		public void startDocument() throws SAXException {
			data.clear();
			datalst.clear();
		}
		
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("stainfo".equals(localName)) {
				position ++;
				String count = attrs.getValue("count");
				if (CommConstant.Rain.DEFAULT_FILTER.equals(count)) {
					count = CommConstant.Rain.DEFAULT_PLACEHOLDER;
				}
				data.put(attrs.getValue("shiduan"), count);
				
				if (position % 4 == 0) {
					data.put("qiangdu", qiangdu[(position / 4) - 1]);
					datalst.add(data);
					data = new HashMap<String,String>();
				}
			} else if ("counttime".equals(localName)) {
				CommConstant.Rain.CALC_TIME = attrs.getValue("value");
			} else if ("comment".equals(localName)) {
				comment = attrs.getValue("value");				
			} else if ("message".equals(localName)) {	
				dialog.cancel();			
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}

	public class RainTotalTableAdapter extends SimpleAdapter {
		public RainTotalTableAdapter(Context context, List<Map<String,String>> data,int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			for (int i = 1 ; i < shiduan.length; i++) {
				final TextView lbl = (TextView)view.findViewById(to[i]);
				if (!CommConstant.Rain.DEFAULT_PLACEHOLDER.equals(lbl.getText())) {
					final int index = position;
					final int sd = i;
					lbl.setTextColor(Color.BLUE);
					lbl.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							Intent intent = new Intent();
							intent.putExtra("name", qiangdu[index]);
							intent.putExtra("shiduan", shiduan[sd]);
							intent.putExtra("qiangdu", strength[index]);
							intent.setClass(getApplicationContext(), RainStationListActivity.class);
							startActivity(intent);
						}						
					});
				}
			}
			
			return view;
		}
	}
	
	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_MAXCOUNT, 2, R.string.menu_maxcount);
		menu.add(0, MENU_KJFB, 3, R.string.menu_kjfb);
		menu.add(0, MENU_INTERVAL, 4, R.string.menu_interval);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {	
		Intent intent = new Intent();	
		switch (item.getItemId()) {
			case MENU_MAXCOUNT:
				intent.setClass(getApplicationContext(), RainMaxCoutActivity.class);
				startActivity(intent);
				return true;
			case MENU_KJFB:
				intent.setClass(getApplicationContext(), RainSpaceActivity.class);
				startActivity(intent);
				return true;
			case MENU_INTERVAL:	
				intent.setClass(getApplicationContext(), RainIntervalActivity.class);
				startActivity(intent);
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onDestroy() {
		super.onDestroy();
		diviservice.closeDB();
		vallservice.closeDB();
        ActivityStackControlUtil.remove(this);
	}
}